<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2018/1/23
 * Time: 下午3:59
 */

namespace Lm\Controllers;

use Admin\Models\hrm\XhhrmDepart;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Admin\Models\lm\XHLmCar;
use Admin\Models\lm\XHLmUseCar;

class StateCarController extends ControllerBase
{


    /**
     * 主页
     *
     * create by dale 20180124
     */
    public function indexAction(){
        $this->view->pick('state_car/index');
        Assets::importJs('js/state_car/index.js');

        $this->view->setVars([
            'targets' => $this->targetConfig(),
        ]);
    }
    /**
     * 柱状图+数据表格
     *
     * @param $target
     * @param bool $showList
     *
     * create by dale 20180124
     */
    public function carChartAction($target,$showList=false){
        $this->view->pick('state_car/carChart');
        Assets::xhChart();
        if($showList){
           Assets::easyUI();
           Assets::importMainJs('assets/xh/xhDatagrid.js');
           $listSearchArr = [];
//           $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
//           $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
//           if($target == 'dep'){
//               $deps  = XhhrmDepart::find([
//                   'columns'    => 'iDepId,sDepName',
//                   'conditions' => 'bDelete = 0 AND iParentId = 0',
//               ])->toArray();
//               $deps = array_column($deps,'sDepName','iDepId');
//               $deps[''] = '请选择部门';
//               $listSearchArr[] = array('type' => 'select', 'id' => 'select_dep', 'data' => $deps, 'default' => '');
//           }
            $listSearchArr[] = array('type' => 'button', 'id' => 'excel_export', 'text' => '导出excel', 'icon' => 'fa fa-file-excel-o');
           $varArr['carList']  = Template::createList('list', 'car-'.$target, [
               'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
           ]);
        }
        Assets::importJs('js/state_car/carChart.js');
        $varArr['target'] = $target;
        $varArr['showList'] = $showList;
        $varArr['startDay']= date('Y-m-d',strtotime('-30 days'));
        $varArr['endDay']   = date('Y-m-d',time());
        $this->view->setVars($varArr);
    }


    /**
     * 获取柱状图数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180124
     */
    public function getDataAction(){
        $tag = $this->request->getPost('tag');
        $startDay = $this->request->getPost('startDay','string');
        $endDay   = $this->request->getPost('endDay','string');
        if (!$startDay && !$endDay) {
            $startDay = date('Y-m-d',strtotime('-30 days'));
            $endDay   = date('Y-m-d',time());
        }
        $builder = $this->modelsManager->createBuilder()
                   ->columns('iUCId,iDepId,iCarId,tRealStart,tStartTime,tRealEnd,tEndTime')
                   ->from('Admin\Models\lm\XHLmUseCar')
                   ->where('bDelete = 0 AND iState != 4');
        $builder->andWhere(" DATE_FORMAT(tRealEnd,'%Y-%m-%d') >= :startDay: AND DATE_FORMAT(tRealEnd,'%Y-%m-%d') <= :endDay: ",
            ['startDay'=>$startDay,'endDay' => $endDay]);
        if($tag == 'dep'){
            $xList  = XhhrmDepart::find([
                'columns'    => 'iDepId,sDepName',
                'conditions' => 'bDelete = 0 AND iParentId = 0',
            ])->toArray();
            $xList = array_column($xList,'sDepName','iDepId');

            $series = [['name' => '部门用车情况','source'=>'num']];
            $builder->columns("count(iUCId) as num ,iDepId")->groupBy('iDepId');
            $data = $builder->getQuery()->execute()->toArray();
            $data = array_column($data,'num','iDepId');
            $num  = [];
            foreach ($xList as $key =>$value){
                $num[] = isset($data[$key]) ? intval($data[$key]) : 0 ;
            }
        }else if($tag == 'country'){
            $data = $builder->andWhere('sCountry is not null AND iCarId is not null')
                        ->columns('count(iUCId) as num,sCountry')
                        ->groupBy('sCountry')->getQuery()->execute()->toArray();
            $xList = array_values(array_column($data,'sCountry'));
            $num = array_values(array_column($data,'num'));
            $series = [['name' => '区域用车情况','source'=>'num']];
        }else if($tag == 'driver'){
            $data = $builder->andWhere('sDriverName is not null AND iCarId is not null')
                ->columns('count(iUCId) as num,sDriverName')
                ->groupBy('sDriverName')->getQuery()->execute()->toArray();
            $xList = array_values(array_column($data,'sDriverName'));
            $num = array_values(array_column($data,'num'));
            $series = [['name' => '司机用车情况','source'=>'num']];
        }else if($tag == 'carType'){
            $data = $builder->andWhere('iCarId is not null')
                ->columns('count(iUCId) as num,iCarId')
                ->groupBy('iCarId')->getQuery()->execute()->toArray();
            $xList = array_values(array_column($data,'iCarId'));
            $carEum =XHLmCar::getPlate();
            foreach ($xList as $index => $value){
                $xList[$index] = $carEum[$value];
            }
            $num = array_values(array_column($data,'num'));
            $series = [['name' => '车型使用情况','source'=>'num']];
        }else {
            $data = $builder->andWhere('iCarId is not null')
                    ->columns("count(iUCId) as num,DATE_FORMAT(tRealEnd,'%Y-%m-%d') as time")
                    ->groupBy('time')->getQuery()->execute()->toArray();
            $data = array_column($data,'num','time');
            $xList = [];
            $num   = [];
            for ($i = strtotime($startDay);$i<=strtotime($endDay);$i=$i+24*3600){
                $time = date('Y-m-d',$i);
                $xList[] = $time;
                $num[]   = isset($data[$time]) ? $data[$time] : 0;
            }
            $series = [['name' => '车型使用情况','source'=>'num']];
        }
        return $this->sendJsonResponse([
            'num'    => $num,
            'series' => $series,
            'xList'  => array_values($xList)
        ]);
    }

    /**
     * 获取数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180125
     */
    public function getDgDataAction(){
        $tag = $this->request->getPost('tag');
        $startDay = $this->request->getPost('startDay','string');
        $endDay   = $this->request->getPost('endDay','string');

        if (!$startDay && !$endDay) {
            $startDay = date('Y-m-d',strtotime('-30 days'));
            $endDay   = date('Y-m-d',time());
        }
        $data = $this->getDataSource($startDay,$endDay,$tag);
        return $this->sendJsonResponse($data);
    }


    public function exportExcelAction($tag,$startDay,$endDay){
        $this->view->disable();
        $source = $this->getDataSource($startDay,$endDay,$tag);
        $source = $source['rows'];
        $titleArr = [];
        if($tag == 'dep'){
            $titleArr = [
                'iDepId' => '部门',
                'num' => '次数',
            ];
        }else if($tag == 'country'){
            $titleArr = [
                'sCountry' => '城市',
                'num' => '次数',
            ];
        }else if($tag == 'driver'){
            $titleArr = [
                'sDriverName' => '司机',
                'num' => '次数',
            ];
        }else if($tag == 'carType'){
            $titleArr = [
                'sCarType' => '车牌',
                'num' => '次数',
            ];
        }else if($tag == 'carState'){
            $titleArr = [
                'time' => '日期',
                'num' => '次数',
            ];
        }
        $data = [];
        foreach ($source as $key => $row) {
            foreach ($titleArr as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        Tool::exportExcelOnline('车辆统计'.$startDay.'~'.$endDay,$titleArr,$data);
    }

    private function getDataSource($startDay,$endDay,$tag){
        $builder = $this->modelsManager->createBuilder()
            ->columns('iUCId,iDepId,iCarId,tRealStart,tStartTime,tRealEnd,tEndTime')
            ->from('Admin\Models\lm\XHLmUseCar')
            ->where('bDelete = 0 AND iState != 4');
        $builder->andWhere(" DATE_FORMAT(tRealEnd,'%Y-%m-%d') >= :startDay: AND DATE_FORMAT(tRealEnd,'%Y-%m-%d') <= :endDay: ",
            ['startDay'=>$startDay,'endDay' => $endDay]);
        if($tag == 'dep'){
            $xList  = XhhrmDepart::find([
                'columns'    => 'iDepId,sDepName',
                'conditions' => 'bDelete = 0 AND iParentId = 0',
            ])->toArray();
            $xList = array_column($xList,'sDepName','iDepId');
            $builder->columns("count(iUCId) as num ,iDepId")->groupBy('iDepId');
            $data = $builder->getQuery()->execute()->toArray();
            $data = array_column($data,'num','iDepId');
            $num  = [];
            foreach ($xList as $key =>$value){
                $num[] = ['num'=>(isset($data[$key]) ? intval($data[$key]) : 0 ),'iDepId'=>$value];
            }
            $data = ['rows'=>$num,'total'=>count($num)];
        }else if($tag == 'country'){
            $builder->columns("count(iUCId) as num ,sCountry")
                ->andWhere('iCarId is not null')->groupBy('sCountry');
            $data = Main::runBuilderPage($builder);
        }else if($tag == 'driver'){
            $builder->columns("count(iUCId) as num ,sDriverName")
                ->andWhere('iCarId is not null')->groupBy('sDriverName');
            $data = Main::runBuilderPage($builder);
        }else if($tag == 'carType'){
            $builder->columns("count(iUCId) as num ,iCarId")
                ->andWhere('iCarId is not null')->groupBy('iCarId');
            $data = Main::runBuilderPage($builder);
            $carEum =XHLmCar::getPlate();
            foreach ($data['rows'] as $index => $row ){
                $data['rows'][$index]['sCarType'] = $carEum[$row['iCarId']];
            }
        }else if($tag == 'carState'){
            $data = $builder->andWhere('iCarId is not null')
                ->columns("count(iUCId) as num,DATE_FORMAT(tRealEnd,'%Y-%m-%d') as time")
                ->groupBy('time')->getQuery()->execute()->toArray();
            $data = array_column($data,'num','time');
            $arr = [];
            for ($i = strtotime($startDay);$i<=strtotime($endDay);$i=$i+24*3600){
                $time = date('Y-m-d',$i);
                $arr[] = ['time'=>$time,'num'=>(isset($data[$time]) ? $data[$time] : 0)];
            }
            $data = ['rows'=>$arr ,'total' => count($arr)];
        }
        return $data;
    }


    /**
     * 配置项
     *
     * @return array
     *
     * create by dale 20180124
     */
    private function targetConfig(){
        $targets = [
          'dep'     => [
              'title' => '部门用车情况',
              'url'   => $this->url->get('lm/state_car/carChart/dep')
          ],
          'country' => [
              'title' => '区域用车情况',
              'url'   => $this->url->get('lm/state_car/carChart/country')
          ],
          'driver'   => [
              'title' => '司机用车情况',
              'url'   => $this->url->get('lm/state_car/carChart/driver')
          ],
          'carType' => [
              'title' => '车牌',
              'url'   => $this->url->get('lm/state_car/carChart/carType')
          ],
          'carState'=> [
              'title' => '派车情况',
              'url'   => $this->url->get('lm/state_car/carChart/carState')
          ]
        ];

        return $targets;
    }
}